import { Component, Input, forwardRef, OnInit, Output, EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';

import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { GameAssemblyService } from '../game-assembly.service';

@Component({
  selector: 'game-select-app',
  templateUrl: './game-select-app.component.html',
  styleUrls: ['./game-select-app.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => GameSelectAppComponent),
      multi: true
    }
  ]
})
export class GameSelectAppComponent implements ControlValueAccessor, OnInit {
  @Input() modalTitle = '新增';
  @Input() appIds: any[] = [];
  @Input() extraParams: any = {}; // 额外参数
  @Output() selectedEmit = new EventEmitter();

  isAppModalVisible = false;
  _onChange: any = null;

  searchParams: any = {
    name: ''
  };
  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };

  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private services: GameAssemblyService
  ) { }

  ngOnInit(): void {}

  writeValue(val: any) {
    if (val) {
      this.setOfCheckedId = new Set(this.appIds);
      this.loadModalTable();
    }
    this.isAppModalVisible = val;
  }

  registerOnChange(fn: any): void {
    this._onChange = fn;
  }

  registerOnTouched(fn: any): void {
    // this.onTouched = fn;
  }

  handleCancel() {
    this.isAppModalVisible = false;
    this._onChange(false);
  }

  async loadModalTable() {
    try {
      const params = {
        ...this.searchParams,
        ...this.extraParams,
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      }
      this.tableParams.loading = true;
      const {code, data, message}: any = await this.services.getGameListData(params);
      this.tableParams.loading = false;

      if (code === 0) {
        this.tableParams.tableData = data.records || [];
        this.tableParams.total = data.total || 0;
      }
    } catch (error) {
      console.log(error);
    }
  }

  queryTableData() {
    this.tableParams.page = 1;
    this.loadModalTable();
  }

  resetTableData() {
    for (let key in this.searchParams) {
      this.searchParams[key] = '';
    }

    this.tableParams.page = 1;
    this.loadModalTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadModalTable();
  }
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadModalTable();
  }

  submitSelected() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择游戏');
      return
    }
    this.selectedEmit.emit([...this.setOfCheckedId]);
    this.handleCancel();
  }
}
